/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.message;

import com.twolattes.json.Entity;
import com.twolattes.json.Json;
import com.twolattes.json.Marshaller;
import com.twolattes.json.TwoLattes;
import com.twolattes.json.Value;
import hextd.message.MessageFactory.NetworkMessage;
import hextd.server.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Entity
public class MessagePlayerList implements Message {

	private static Marshaller<MessagePlayerList> marshaller;

	@Entity
	public static class MPPlayerInfo {

		@Value
		public int gameId;
		@Value
		public int userId;
		@Value
		public String name;
		@Value
		public int rank;
		@Value
		public int games;
		@Value
		public boolean ready;
	}
	public NetworkMessage type = NetworkMessage.PlayerList;
	public static String key = "PLIST";
	public static Pattern MessagePattern = Pattern.compile(key + ".*");
	//
	@Value
	public List<MPPlayerInfo> players;
	private String message;

	public static String formatMessage(List<Player> players) {
		List<MPPlayerInfo> playerInfoList = new ArrayList<MPPlayerInfo>(players.size());
		for (Player p : players) {
			playerInfoList.add(p.getMPPlayerInfo());
		}
		MessagePlayerList mpl = new MessagePlayerList();
		mpl.players = playerInfoList;
		return key + marshaller.marshall(mpl).toString();
	}

	public MessagePlayerList() {
		if (marshaller == null) {
			marshaller = TwoLattes.createMarshaller(MessagePlayerList.class);
		}
	}

	public List<MPPlayerInfo> getPlayers() {
		return players;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		if (marshaller == null) {
			marshaller = TwoLattes.createMarshaller(MessagePlayerList.class);
		}
		Json.Value fromString = Json.fromString(message.substring(key.length()));
		MessagePlayerList unmarshall = marshaller.unmarshall((Json.Object) fromString);
		unmarshall.message = message;
		return unmarshall;
	}

	@Override
	public int getSenderId() {
		return -1;
	}

	@Override
	public void setSenderId(int id) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Pattern getPattern() {
		return MessagePlayerList.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
